package com.littcore.saap.mgr.web;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.littcore.common.Utility;
import com.littcore.dao.page.IPageList;
import com.littcore.dao.ql.PageParam;
import com.littcore.exception.NotLoginException;
import com.littcore.module.annotation.Func;
import com.littcore.saap.common.vo.TenantUserVo;
import com.littcore.saap.core.common.SaapConstants.IsolatedMode;
import com.littcore.saap.core.common.SaapConstants.TenantOrderType;
import com.littcore.saap.core.module.tenant.config.TenantDefConfig;
import com.littcore.saap.core.module.tenant.config.TenantTypeConfigManager;
import com.littcore.saap.mgr.service.ITenantMgrService;
import com.littcore.saap.mgr.service.ITenantOrderMgrService;
import com.littcore.saap.mgr.service.IUserInfoMgrService;
import com.littcore.saap.system.biz.ITenantBizService;
import com.littcore.saap.system.biz.IUserBizService;
import com.littcore.saap.system.po.Tenant;
import com.littcore.saap.system.po.TenantOrder;
import com.littcore.saap.system.po.UserInfo;
import com.littcore.web.mvc.action.BaseController;
import com.littcore.web.util.WebUtils;




/**
 * 
 * Order controller.
 * <pre><b>Description：</b>
 *    Order Management
 * </pre>
 * 
 * @author <a href="mailto:littcai@hotmail.com">Bob.cai</a>
 * @since 2014-05-14
 * @version 1.0
 */
@Controller
public class TenantOrderMgrController extends BaseController{
	
	private final static Logger logger = LoggerFactory.getLogger(TenantOrderMgrController.class);

	@Resource
	private ITenantOrderMgrService tenantOrderMgrService;
	@Resource
	private ITenantBizService tenantBizService;
	@Resource
	private IUserInfoMgrService userInfoMgrService;
	@Resource
	private ITenantMgrService tenantMgrService;
	@Resource
	private IUserBizService userBizService;
	
	
	
	/**
	 * default page.
	 * 
	 */
	@Func(funcCode="query", moduleCode="mgr.tenantOrder", enableLog=false, enablePermission=false) 
	@RequestMapping 
	public ModelAndView index(WebRequest request, ModelMap modelMap) throws NotLoginException{	
		//get params from request
		String tenantCode = request.getParameter("tenantCode");
		String orderType = request.getParameter("orderType");
				
		//package the params
		PageParam pageParam = WebUtils.getPageParam(request);
		pageParam.addCond("tenantCode", tenantCode);
		if(StringUtils.isNotBlank(orderType)){
			pageParam.addCond("orderType", Integer.parseInt(orderType));	
		}
		pageParam.addCond("isDeleted", false);	
		//Get page result
		IPageList pageList = tenantOrderMgrService.listPage(pageParam);		
		
		//return params to response
		modelMap.addAttribute("pageParam", pageParam);	
		modelMap.addAttribute("pageList", pageList);	
		
		return new ModelAndView("/mgr/tenantOrder/index");	
	
	} 	
	
	
	
	/**
	 * Add Page.
	 * 
	 * @return ModelAndView
	 */	
	@Func(funcCode="add", moduleCode="mgr.tenantOrder", enableLog=false, enablePermission=false)  
	@RequestMapping
	public ModelAndView add(){
		
		List<Tenant> tenantList = tenantMgrService.listAll();
		
	  	return new ModelAndView("/mgr/tenantOrder/add")
	  			.addObject("tenantList", tenantList)
	  			.addObject("tenantOrderType", TenantOrderType.RENEW);
	  	
	}
	
	

	/**
	 * find TenantInfo
	 * 
	 * @return ModelAndView
	 */	
	@RequestMapping(value="findTenantInfo.json")
	public ModelAndView findTenantInfo(@RequestParam int tenantId){
		
		Tenant tenant = tenantMgrService.load(tenantId);
		TenantDefConfig tenantDef = TenantTypeConfigManager.getInstance().getTenantDefConfig(tenant.getBagCode());
		List<TenantUserVo> userInfoList = userBizService.findByTenant(tenantId);
	  	return new ModelAndView("jsonView")
	  			.addObject("tenant", tenant)
	  			.addObject("tenantDef", tenantDef)
	  			.addObject("userInfoList", userInfoList);
	  	
	}
	
	
	/**
	 * 增加订单
	 * @param userId
	 * @param tenantTypeCode
	 * @param tenantCode
	 * @param tenantAlias
	 * @param quantity
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="saveOrder.json")
	public ModelAndView saveOrder(@RequestParam int userId,@RequestParam int tenantId, @RequestParam String tenantTypeCode,@RequestParam String tenantCode,@RequestParam int tenantOrderType,
			                      @RequestParam String tenantAlias, @RequestParam int quantity , HttpServletRequest request) throws Exception{      
		
		  
		TenantDefConfig tenantDef = TenantTypeConfigManager.getInstance().getTenantDefConfig(tenantTypeCode);
	    //TODO 隔离级别暂时为共享，后续可在页面增加选项，同时价格上需要区分
	    Integer orderId = tenantOrderMgrService.save(tenantOrderType, tenantId, tenantCode, tenantAlias, tenantTypeCode, IsolatedMode.NO_ISOLATION, tenantDef.getPrice(), quantity, userId);
	    TenantOrder tenantOrder = tenantOrderMgrService.load(orderId);
	    
	    String orderNo = tenantOrder.getOrderNo();
	    //FIXME 模拟付费
	    tenantOrderMgrService.doPaid(orderNo, "alipay");
	    if(tenantOrderType == TenantOrderType.RENEW){
	    	tenantBizService.doReNew(tenantOrder);
	    }
		
	    return new ModelAndView("jsonView"); 
	    
   }
	
	
	/**
	 * Edit Page.
	 * 
	 * @return ModelAndView
	 */
	@Func(funcCode="edit", moduleCode="mgr.tenantOrder", enableLog=false, enablePermission=false)  
	@RequestMapping 
	public ModelAndView edit(@RequestParam Integer id){ 
		TenantOrder tenantOrder = tenantOrderMgrService.load(id);		
        return new ModelAndView("/system/tenantOrder/edit").addObject("tenantOrder", tenantOrder);
    }	
	
	
	
	/**
	 * Show Order.
	 * 
	 * @param id 
	 * @return ModelAndView
	 * 
	 */
	@Func(funcCode="query", moduleCode="mgr.tenantOrder", enableLog=false, enablePermission=false)  
	@RequestMapping 
	public ModelAndView show(@RequestParam Integer id){ 
		
		TenantOrder tenantOrder = tenantOrderMgrService.load(id);
		UserInfo userInfo = userInfoMgrService.load(tenantOrder.getCreateBy());
		
        return new ModelAndView("/mgr/tenantOrder/show")
        		.addObject("tenantOrder", tenantOrder)
        		.addObject("userInfo", userInfo);
    }   
    
	
	
	/**
	 * Update.
	 * @throws Exception
	 */
	@Func(funcCode="edit",moduleCode="mgr.tenantOrder", enablePermission=false)
	@RequestMapping 
	public void update(WebRequest request, ModelMap modelMap) throws Exception {
		
		TenantOrder tenantOrder = tenantOrderMgrService.load(Utility.parseInt(request.getParameter("id")));
		BeanUtils.populate(tenantOrder, request.getParameterMap());
		tenantOrderMgrService.update(tenantOrder);
		
	}
	
	
	/**
	 * Delete.
	 * @param id id
	 * @throws Exception 
	 */
	@Func(funcCode="delete",moduleCode="mgr.tenantOrder", enablePermission=false)
	@RequestMapping 
	public void delete(@RequestParam Integer id) throws Exception
	{
		tenantOrderMgrService.delete(id);
	}
	
	

	/**
	 * Delete Batch.
	 * @throws Exception
	 */
	@Func(funcCode="delete",moduleCode="mgr.tenantOrder", enablePermission=false)
	@RequestMapping 
	public void deleteBatch(@RequestParam(value="ids[]") Integer[] ids) throws Exception
	{
		tenantOrderMgrService.deleteBatch(ids);
	}
	

}
